package com.qiye.pointsserver.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.qiye.pointsserver.common.PageUtil.PageParam;
import com.qiye.pointsserver.common.PageUtil.PageResult;
import com.qiye.pointsserver.common.result.Result;
import com.qiye.pointsserver.model.dto.UserInfoAddDto;
import com.qiye.pointsserver.model.entity.Pointslog;
import com.qiye.pointsserver.model.entity.User;
import com.qiye.pointsserver.model.entity.Userinfo;
import com.qiye.pointsserver.model.vo.UserInfoVO;
import com.qiye.pointsserver.service.PointslogService;
import com.qiye.pointsserver.service.UserService;
import com.qiye.pointsserver.service.UserinfoService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Tag(name = "02.用户信息模块")
@RestController
@RequestMapping("/api/v1/userinfo")
@RequiredArgsConstructor
@Slf4j
public class UserinfoController {

    @Resource
    private UserinfoService userinfoService;

    @Resource
    private UserService userService;

    @Resource
    private PointslogService pointslogService;

    @Operation(summary = "新增用户信息")
    @PostMapping("/add")
    public Result add(@RequestBody UserInfoAddDto userInfoAddDto){
        // 正则判断手机号是否合理
        String phone = userInfoAddDto.getPhone();

        if (phone == null || !phone.matches("^1[3-9]\\d{9}$")) {
           return Result.failed("手机号格式不正确");
        }
        Userinfo userinfo = new Userinfo();
        userinfo.setUserId(userInfoAddDto.getUserId());
        userinfo.setName(userInfoAddDto.getName());
        userinfo.setPhone(userInfoAddDto.getPhone());
        userinfo.setCompany(userInfoAddDto.getCompany());
        userinfo.setGender(userInfoAddDto.getGender());
        userinfo.setBirthdate(userInfoAddDto.getBirthdate());
        userinfoService.save(userinfo);
        return Result.success("个人信息添加成功");
    }

    @Operation(summary = "修改用户信息")
    @PostMapping("/update")
    public Result update(@RequestBody UserInfoAddDto userInfoAddDto) {
        LambdaUpdateWrapper<Userinfo> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Userinfo::getUserId, userInfoAddDto.getUserId());

        Map<String, Object> fieldMap = new HashMap<>();
        fieldMap.put("name", userInfoAddDto.getName());
        fieldMap.put("phone", userInfoAddDto.getPhone());
        fieldMap.put("company", userInfoAddDto.getCompany());
        fieldMap.put("gender", userInfoAddDto.getGender());
        fieldMap.put("birthdate", userInfoAddDto.getBirthdate());

        // 手机号特殊处理
        String phone = userInfoAddDto.getPhone();
        if (phone != null && !phone.matches("^1[3-9]\\d{9}$")) {
            return Result.failed("手机号格式不正确");
        }

        // 字段设置
        Optional.ofNullable(userInfoAddDto.getName()).ifPresent(name -> updateWrapper.set(Userinfo::getName, name));
        Optional.ofNullable(phone).ifPresent(p -> updateWrapper.set(Userinfo::getPhone, p));
        Optional.ofNullable(userInfoAddDto.getCompany()).ifPresent(c -> updateWrapper.set(Userinfo::getCompany, c));
        Optional.ofNullable(userInfoAddDto.getGender()).ifPresent(g -> updateWrapper.set(Userinfo::getGender, g));
        Optional.ofNullable(userInfoAddDto.getBirthdate()).ifPresent(b -> updateWrapper.set(Userinfo::getBirthdate, b));

        updateWrapper.set(Userinfo::getUpdateTime, LocalDateTime.now());
        userinfoService.update(updateWrapper);
        return Result.success("个人信息修改成功");
    }

    @Operation(summary = "根据userid获取用户信息")
    @GetMapping("/get")
    public Result get(@RequestParam Integer userId) {
        UserInfoVO vo = userinfoService.getUserInfoByUserId(userId);
        return Result.success(vo);

    }

    @Operation(summary = "关键词分页查询")
    @PostMapping("/search")
    public Result searchUserInfo(@RequestBody PageParam pageParam) {
        PageResult<UserInfoVO> userinfoVOList = userinfoService.searchUserInfo(pageParam);
        return Result.success(userinfoVOList);
    }

    @Operation(summary = "通过ID删除用户信息-用户账号-用户积分信息")
    @GetMapping("/delete/{id}")
    @Transactional
    public Result delete(@PathVariable Integer id) {
        LambdaQueryWrapper<Userinfo> queryWrapper = new LambdaQueryWrapper<>();
        // 提取该条记录中的userid
        queryWrapper.eq(Userinfo::getId, id);
        Userinfo userinfo = userinfoService.getOne(queryWrapper);
        Integer userId = userinfo.getUserId();
        LambdaQueryWrapper<User> userQueryWrapper = new LambdaQueryWrapper<>();
        userQueryWrapper.eq(User::getId, userId);
        LambdaQueryWrapper<Pointslog> pointslogLambdaQueryWrapper = new LambdaQueryWrapper<>();
        pointslogLambdaQueryWrapper.eq(Pointslog::getUserinfoId,id);
        try{
            userinfoService.removeById(id);
            userService.removeById(userId);
            pointslogService.remove(pointslogLambdaQueryWrapper);
            return Result.success("删除成功");
        }catch (Exception e){
            System.out.println(e);
            return Result.failed("删除失败");
        }
    }

    @Operation(summary = "通过ID获取用户信息")
    @GetMapping("/getUserInfoid/{id}")
    public Result getUserInfoid(@PathVariable Integer id){
        LambdaQueryWrapper<Userinfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Userinfo::getUserId,id);
        Userinfo userinfo = userinfoService.getOne(queryWrapper);
        return Result.success(userinfo);
    }
}
